import { defineStore } from 'pinia'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import api from '@/utils/api'
import { storeLogger } from '@/utils/logger'

export const useKafkaMonitorStore = defineStore('kafkaMonitor', () => {
  // 状态
  const monitors = ref([])
  const loading = ref(false)
  const total = ref(0)           // 当前筛选条件下的总数
  const totalAll = ref(0)        // 全部数据的总数
  const stats = ref({            // 统计数据
    active_count: 0,
    monitored_count: 0,
    alert_enabled_count: 0,
    alerting_count: 0
  })
  const currentPage = ref(1)
  const pageSize = ref(20)
  
  // 搜索条件
  const searchForm = ref({
    topic_name: '',
    status: '',
    is_monitored: null,  // 使用null而不是空字符串，匹配数字类型
    is_alert_enabled: null,  // 使用null而不是空字符串，匹配数字类型
    alert_status: ''
  })
  
  // 排序条件
  const sortField = ref('last_alert_time')
  const sortOrder = ref('desc')
  
  // 获取监控列表
  const fetchMonitors = async (configId, params = {}) => {
    try {
      if (!configId) {
        throw new Error('缺少config_id参数')
      }
      
      loading.value = true
      const queryParams = {
        config_id: configId,
        ...searchForm.value,
        page: currentPage.value,
        pageSize: pageSize.value,
        sort: sortField.value,
        order: sortOrder.value,
        ...params
      }
      
      // 如果传入了字段参数，添加到查询参数中
      if (params.fields && params.fields.length > 0) {
        queryParams.fields = params.fields.join(',')
      }
      
      // 清理空值（但保留config_id）
      Object.keys(queryParams).forEach(key => {
        if (key !== 'config_id' && (queryParams[key] === '' || queryParams[key] === null || queryParams[key] === undefined)) {
          delete queryParams[key]
        }
      })
      
      storeLogger.debug('Fetching kafka monitors with params', queryParams)
      
      const response = await api.get('/kafka-topic-monitor/list', { params: queryParams })
      const payload = response.data || {}
      const data = payload.success ? (payload.data || {}) : payload
      
      monitors.value = data.monitors || []
      total.value = data.total || 0
      
      // 更新统计信息
      if (data.stats) {
        stats.value = data.stats
      }
      
      storeLogger.info('Kafka monitors fetched successfully', {
        count: monitors.value.length,
        total: total.value,
        page: currentPage.value,
        configId
      })
      
      return response.data
    } catch (error) {
      storeLogger.error('Failed to fetch kafka monitors', error)
      ElMessage.error('获取监控列表失败')
      throw error
    } finally {
      loading.value = false
    }
  }
  
  // 获取单个监控详情
  const getMonitorDetail = async (monitorId) => {
    try {
      const response = await api.get(`/kafka-topic-monitor/${monitorId}`)
      return response.data
    } catch (error) {
      storeLogger.error('Failed to fetch monitor detail', error)
      ElMessage.error('获取监控详情失败')
      throw error
    }
  }
  
  // 更新监控配置
  const updateMonitor = async (monitorId, data) => {
    try {
      const response = await api.put(`/kafka-topic-monitor/update/${monitorId}`, data)
      if (response.data.success) {
        ElMessage.success('更新成功')
      }
      return response.data
    } catch (error) {
      storeLogger.error('Failed to update monitor', error)
      ElMessage.error('更新失败')
      throw error
    }
  }
  
  // 删除监控记录
  // 立即查询单个topic的最新数据
  const queryTopicNow = async (configId, topicName, partitionId) => {
    try {
      const response = await api.post('/kafka-topic-monitor/query-now', {
        config_id: configId,
        topic_name: topicName,
        partition_id: partitionId
      })
      
      if (response.data.success) {
        storeLogger.info('Topic query successful', { topicName, partitionId })
      }
      return response.data
    } catch (error) {
      storeLogger.error('Failed to query topic now', error)
      throw error
    }
  }
  
  // 批量更新监控配置
  const batchUpdateMonitors = async (ids, data, configId = null) => {
    try {
      const requestData = {
        update_data: data  // 修正参数名，匹配后端期望的 update_data
      }
      
      // 如果提供了configId且没有ids，则按config_id更新所有记录
      if (configId && (!ids || ids.length === 0)) {
        requestData.config_id = configId
      } else {
        requestData.monitor_ids = ids  // 修正参数名，匹配后端期望的 monitor_ids
      }
      
      const response = await api.post('/kafka-topic-monitor/batch-update', requestData)
      if (response.data.success) {
        ElMessage.success(response.data.message || '批量更新成功')
      }
      return response.data
    } catch (error) {
      storeLogger.error('Failed to batch update monitors', error)
      ElMessage.error('批量更新失败')
      throw error
    }
  }
  
  // 批量删除监控记录
  const batchDeleteMonitors = async (ids) => {
    try {
      const response = await api.post('/kafka-topic-monitor/batch-delete', { ids })
      if (response.data.success) {
        ElMessage.success(response.data.message || '批量删除成功')
      }
      return response.data
    } catch (error) {
      storeLogger.error('Failed to batch delete monitors', error)
      ElMessage.error('批量删除失败')
      throw error
    }
  }
  
  // 重置告警状态
  const resetAlertStatus = async (monitorId) => {
    try {
      const response = await api.post(`/kafka-topic-monitor/reset-alert/${monitorId}`)
      if (response.data.success) {
        ElMessage.success('告警状态已重置')
      }
      return response.data
    } catch (error) {
      storeLogger.error('Failed to reset alert status', error)
      ElMessage.error('重置失败')
      throw error
    }
  }
  
  // 获取Kafka配置列表
  const fetchKafkaConfigs = async () => {
    try {
      const response = await api.get('/kafka-topic-monitor/kafka-configs')
      return response.data
    } catch (error) {
      storeLogger.error('Failed to fetch kafka configs', error)
      throw error
    }
  }
  
  // 获取Topic列表（指定Kafka环境下的所有Topic）
  const fetchTopicsList = async (configId) => {
    try {
      const response = await api.get('/kafka-topic-monitor/topics-list', {
        params: { config_id: configId }
      })
      return response.data
    } catch (error) {
      storeLogger.error('Failed to fetch topics list', error)
      throw error
    }
  }
  
  // 获取批次执行记录
  const fetchBatchRecords = async (page = 1, pageSize = 20) => {
    try {
      const response = await api.get('/kafka-topic-monitor/batch-records', {
        params: { page, pageSize }
      })
      return response.data
    } catch (error) {
      storeLogger.error('Failed to fetch batch records', error)
      ElMessage.error('获取批次记录失败')
      throw error
    }
  }
  
  // 重置搜索条件
  const resetSearch = () => {
    searchForm.value = {
      topic_name: '',
      status: '',
      is_monitored: null,  // 使用null而不是空字符串，匹配数字类型
      is_alert_enabled: null,  // 使用null而不是空字符串，匹配数字类型
      alert_status: ''
    }
    currentPage.value = 1
  }
  
  return {
    // 状态
    monitors,
    loading,
    total,
    totalAll,
    stats,
    currentPage,
    pageSize,
    searchForm,
    sortField,
    sortOrder,
    
    // 方法
    fetchMonitors,
    getMonitorDetail,
    updateMonitor,
    queryTopicNow,
    batchUpdateMonitors,
    batchDeleteMonitors,
    resetAlertStatus,
    fetchKafkaConfigs,
    fetchTopicsList,
    fetchBatchRecords,
    resetSearch
  }
})

